<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>数字华容道</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            list-style: none;
        }

        /* 游戏整体容器样式 */
        .game-wrapper {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 30px;
        }

        /* 倒计时显示区域样式 */
        #timer {
            font-size: 30px;
            color: #e4b77c;
            margin-bottom: 20px;
        }

        ul {
            width: 310px;
            background-color: #421c0f;
            display: flex;
            flex-wrap: wrap;
            border: 5px solid #421c0f;
            border-radius: 5px;
        }

        li {
            width: 100px;
            height: 100px;
            background-color: #e4b77c;
            border: 1px solid #421c0f;
            line-height: 100px;
            font-weight: bold;
            text-align: center;
            font-size: 30px;
            cursor: pointer;
        }

        li.empty {
            background-color: #421c0f;
        }

        button {
            display: block;
            margin: 10px auto;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            /* 以下是让按钮边框和九宫格一致的样式 */
            border: 5px solid #421c0f;
            border-radius: 5px;
            background-color: #e4b77c;
            color: #421c0f;
        }
    </style>
</head>

<body>
    <!-- 游戏整体容器 -->
    <div class="game-wrapper">
        <!-- 倒计时显示区域 -->
        <div id="timer">05:00</div>
        <ul id="puzzle"></ul>
    </div>
    <button id="shuffleButton">开始游戏</button>
    <script>
        const puzzle = document.getElementById('puzzle');
        const shuffleButton = document.getElementById('shuffleButton');
        const timerElement = document.getElementById('timer');
        let numbers = [1, 2, 3, 4, 5, 6, 7, 8, null];
        let timer;
        let timeLeft = 300; // 5 分钟，单位为秒

        // 计算逆序数
        function countInversions(arr) {
            let inversions = 0;
            const flatArr = arr.flat();
            for (let i = 0; i < flatArr.length - 1; i++) {
                for (let j = i + 1; j < flatArr.length; j++) {
                    if (flatArr[i]!== null && flatArr[j]!== null && flatArr[i] > flatArr[j]) {
                        inversions++;
                    }
                }
            }
            return inversions;
        }

        // 打乱数组
        function shuffle(array) {
            let newArray;
            do {
                newArray = array.slice();
                for (let i = newArray.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
                }
            } while (countInversions(newArray) % 2!== countInversions(numbers) % 2);
            return newArray;
        }

        // 渲染拼图
        function renderPuzzle() {
            puzzle.innerHTML = '';
            numbers.forEach((number) => {
                const li = document.createElement('li');
                if (number === null) {
                    li.classList.add('empty');
                } else {
                    li.textContent = number;
                }
                li.addEventListener('click', () => moveTile(number));
                puzzle.appendChild(li);
            });
        }

        // 移动方块
        function moveTile(tile) {
            const emptyIndex = numbers.indexOf(null);
            const tileIndex = numbers.indexOf(tile);
            const isAdjacent =
                (Math.abs(emptyIndex - tileIndex) === 1 && Math.floor(emptyIndex / 3) === Math.floor(tileIndex / 3)) ||
                Math.abs(emptyIndex - tileIndex) === 3;

            if (isAdjacent) {
                [numbers[emptyIndex], numbers[tileIndex]] = [numbers[tileIndex], numbers[emptyIndex]];
                renderPuzzle();
                checkWin();
            }
        }

        // 检查是否完成游戏
        function checkWin() {
            const winningOrder = [1, 2, 3, 4, 5, 6, 7, 8, null];
            if (JSON.stringify(numbers) === JSON.stringify(winningOrder)) {
                clearInterval(timer);
                alert('挑战成功');
            }
        }

        // 倒计时函数
        function startTimer() {
            timer = setInterval(() => {
                if (timeLeft > 0) {
                    const minutes = Math.floor(timeLeft / 60);
                    const seconds = timeLeft % 60;
                    timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                    timeLeft--;
                } else {
                    clearInterval(timer);
                    alert('挑战失败，时间已到！');
                }
            }, 1000);
        }

        // 初始化游戏，直接渲染正常顺序
        renderPuzzle();

        // 为“开始游戏”按钮添加点击事件
        shuffleButton.addEventListener('click', () => {
            numbers = shuffle(numbers);
            renderPuzzle();
            timeLeft = 300; // 重置时间
            timerElement.textContent = '05:00';
            clearInterval(timer); // 清除之前的定时器
            startTimer(); // 开始新的倒计时
        });
    </script>
</body>

</html>